/**
 *
 */
package com.wedroid.r2d2.support.response;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wedroid.r2d2.support.BaseResponse;

/**
 * @author lute
 */
public abstract class AbstractBaseResponse implements DroidResponse {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    private static final String EMOJI_REGEX = "<span class=\\\\\"emoji emoji([0-9a-f]{4,5})\\\\\"></span>";

    private static final Pattern emojiPattern = Pattern.compile(EMOJI_REGEX);

    private BaseResponse baseResponse;

    /* (non-Javadoc)
     * @see com.wedroid.r2d2.support.response.DroidResponse#isSuccess()
     */
    public boolean isSuccess() {
        return baseResponse != null && baseResponse.isSuccess();
    }

    /* (non-Javadoc)
     * @see com.wedroid.r2d2.support.response.DroidResponse#parse(java.lang.String)
     */
    public void parse(String body) {
        JSONObject object = JSON.parseObject(transformEmoji(body));
        baseResponse = object.getObject("BaseResponse", BaseResponse.class);
        if (isSuccess()) {
            parseInternal(object);
        } else {
            logger.trace("#parse - Get base response code [{}] and error message [{}].", baseResponse.getRet(), baseResponse.getErrMsg());
        }
    }

    /**
     * @param value
     * @return
     */
    protected String transformEmoji(String value) {
        Matcher matcher = emojiPattern.matcher(value);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String hex = matcher.group(1);
            String unicodeString = new String(Character.toChars(Integer.parseInt(hex, 16)));
            matcher.appendReplacement(sb, unicodeString);
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * @param object
     */
    protected abstract void parseInternal(JSONObject object);

    /**
     * @return
     */
    public String getErrorMessage() {
        if (baseResponse != null) {
            return baseResponse.getErrMsg();
        }
        return null;
    }

}
